/* eslint-disable no-console */
/* eslint-disable camelcase */
import React, { Component } from "react";
import { connect } from "react-redux";
import { Toast, Modal } from "antd-mobile";
import { Base64 } from "js-base64";
// 组件
import MainLayout from "@component/mainLayout/mainLayout";
import HaveBankCard from "./component/haveBankCard";
import NoBankCard from "./component/noBankCard";
import Banner from "@/views/viewCommon/Banner";
import { openWebView } from "@tools/native/navigate";
import { getAppPlatformsDatas } from "../../../../Redux/Action/nativeDatas/nativeDatas";
import { setRepaymentMoney } from "../../../../Redux/Action/repayment/repaymentMoney";
import yhTools from "@tools/yh";
import { InterfaceG } from "@config/Config";
import { dropByCacheKey } from "react-router-cache-route";
const modalAlert = Modal.alert;

import "./xhfRepayment.scss";
import iconZfb from "@images/icon_zfb.png";
import iconCheck from "@images/icon/icon_hui_check.png";
import iconChecked from "@images/icon/icon-checked.png";
import questionLine from "@images/imageXHF/question-line.png";

/**
 * 描述：小辉付还款
 * 作者：zenghq
 * 日期：2020-08-20
 */
@connect(
	state => ({
		...state,
		bankReducer: state.bankReducer
	}),
	dispatch => ({
		_setRepaymentMoney: value => dispatch(setRepaymentMoney(value)),
		_getAppPlatformsDatas: options => {
			dispatch(getAppPlatformsDatas(options));
		}
	})
)
class xhfRepayment extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showAlipayRepaymentBtn: false, // 是否展示支付宝还款按钮
			amount: undefined, // 还款金额
			selectedBank: undefined, // 还款银行卡
			selectTools: {
				// 支付方式选择状态
				alipay: false,
				bankcard: false
			},
			bannerList: []
		};
		this.version = this.props.getAppPlatformsDatas.sdkVersionCode || "1.0.1";
	}
	componentDidMount = () => {
		this.initData();
		this.getUserBank();
		this.getBannerList();
	};
	componentWillUnmount = () => { };
	/**获取初始化数据 */
	initData() {
		const { data } = this.props.match.params;
		if (data) {
			let pageParams = JSON.parse(data);
			this.setState({
				pageParams
			});
			this.props._setRepaymentMoney({
				totalLoanFee: pageParams.billAmount,
				type: "pay"
			});
			this.setState({
				amount: pageParams.billAmount,
				// showAlipayRepaymentBtn: pageParams.showAlipayRepaymentBtn,
				selectTools: {
					// 支付方式选择状态
					alipay: pageParams.showAlipayRepaymentBtn,
					bankcard: false
				}
			});
		}
	}
	/**获取可以还款的银行卡 */
	getUserBank = () => {
		const params = {
			url: InterfaceG.getUserBank,
			params: {
				type: "1", //1：默认  2：全部
				productCategory: "601" //产品大类 小辉付：601，小辉贷：802，好借：2000
			},
			_alertShow: false
		};
		Toast.loading("", 10);
		yhTools.request(params).then(res => {
			Toast.hide();
			if (res.code == "0") {
				let { bankCardVos, showAlipayRepaymentBtn } = res.data;
				if (this.props.bankReducer.selectedBankCard.bindCardNo) {
					let bank = this.props.bankReducer.selectedBankCard;
					let selectedBank = {
						bankAccount: bank.cardNo,
						bankCode: bank.bindCardNo,
						bankName: bank.bankName,
						logurl: bank.logoUrl,
						maxAmt: bank.dayAmount
					};
					this.setState({
						selectedBank: selectedBank
					});
					this.changePaytool("bankcard");
				} else {
					for (let i = 0; i < bankCardVos.length; i++) {
						if (bankCardVos[i].isDefault == "1") {
							this.setState({
								selectedBank: bankCardVos[i]
							});
							this.changePaytool("bankcard");
							break;
						}
					}
				}

				const { selectedBank } = this.state;
				//默认还款方式逻辑：首先默认银行卡还款，当无绑定的银行卡，且Sdk版本支持支付宝，就默认支付宝
				//有卡就默认卡
				if (selectedBank && selectedBank.bankCode) {
					this.setState({
						selectTools: {
							// 支付方式选择状态
							alipay: false,
							bankcard: true
						}
					});
				} else if (
					showAlipayRepaymentBtn &&
					yhTools.isSupportAlipay(this.version) &&
					!selectedBank
				) {
					//接口返回支持支付宝，并且sdk版本支持支付宝
					// 有支付宝并且没有选择的卡就默认支付宝
					this.setState({
						selectTools: {
							// 支付方式选择状态
							alipay: true,
							bankcard: false
						}
					});
				}
				this.setState({
					showAlipayRepaymentBtn
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	/**
	 * 支付宝还款
	 */
	async repaymentAlipayClick(repaymentData) {
		const { requestData } = repaymentData;
		if (requestData) {
			let decRequest_data = Base64.decode(requestData);
			yhTools
				.openRepaymentAlipayView({ request_data: decRequest_data })
				.then(alipayResp => {
					if (alipayResp.status === "1000") {
						const params = {
							billNo: this.state.pageParams.billNo,
							type: "1" //1:小辉付，2:小辉贷
						};
						this.props.history.push({
							pathname: "/xhfAlipayRet",
							state: { ...params, goPath: "xhfHomeCredit" }
						});
					} else if (alipayResp.status === "8000") {
						Toast.info("正在处理中", 2);
					} else if (alipayResp.status === "4000") {
						Toast.info("还款失败", 2);
					} else if (alipayResp.status === "5000") {
						Toast.info("重复请求", 2);
					} else if (alipayResp.status === "6001") {
						let cancelParams = {
							url: InterfaceG.xhfRepaymentByAlipayCancel,
							params: {
								billNo: this.state.pageParams.billNo
							},
							_alertShow: false
						};
						yhTools.request(cancelParams).then(resp => {
							if (resp.code === "0") {
								Toast.info("还款取消", 2);
							}
						});
					} else if (alipayResp.status === "6002") {
						Toast.info("网络连接出错", 2);
					}
				});
		} else {
			Toast.info("获取请求数据失败", 2);
		}
	}
	//点击
	submitPay = () => {
		//是否与连连签约，如果已签约，直接使用连连支付，否则先去签约
		const { amount, selectedBank, pageParams, selectTools } = this.state;
		if (selectTools["alipay"] && yhTools.isSupportAlipay(this.version)) {
			//支付宝预下单
			const params = {
				url: InterfaceG.xhfRepaymentByAlipayOrWx,
				params: {
					amount: amount, //还款金额
					billNo: pageParams.billNo, //账单编号
					repayMean: "1", //还款方式，1，支付宝，2，银行卡，3，微信
					repayMark: pageParams.repayMark, //提前还款标识：1，非提前还款不传；2，已出账全额还款
					unAccountAmount: pageParams.unAccountAmount, //未出账金额
					unRepayAmount: pageParams.unRepayAmount //未结清金额
				},
				_alertShow: false
			};
			Toast.loading("正在提交中...", 10);
			yhTools
				.request(params)
				.then(res => {
					Toast.hide();
					const data = res.data;
					if (res.code === "0") {
						this.repaymentAlipayClick(data);
					} else {
						Toast.info(res.message, 2);
					}
				})
				.catch(() => {
					Toast.hide();
				});
		} else if (selectTools["bankcard"]) {
			//银行卡预下单
			const params = {
				url: InterfaceG.xhfRepayment,
				params: {
					amount: amount, //还款金额
					bill_amount: amount, //还款金额
					bank_code: selectedBank ? selectedBank.bankCode : "", //银行卡Code
					billNo: pageParams.billNo, //账单编号
					method: selectTools["alipay"] ? "alipay" : "bankcard",
					repayMark: pageParams.repayMark,
					unAccountAmount: pageParams.unAccountAmount,
					unRepayAmount: pageParams.unRepayAmount
				},
				_alertShow: false
			};
			Toast.loading("正在提交中...", 10);
			yhTools
				.request(params)
				.then(res => {
					Toast.hide();
					const data = res.data;
					if (res.code === "0") {
						//pageIndex跳转页面:0-认证支付签约页面    1-认证支付还款页面
						const pageIndex = data.pageIndex;
						if (pageIndex == "0") {
							this.props.history.push({
								pathname: `/authenticatePay/${JSON.stringify({
									fromType: this.state.pageParams.fromType,
									...data,
									orderNo: data.orderNo, //签约订单号 pageIndex=0
									bankCode: params.params.bank_code, //银行账户key
									amount: this.state.amount,
									bankMobile: data.bank_mobile, //银行预留手机号
									accountName: data.account_name, //账户名
									cardNo: data.card_no, //卡号
									idNo: data.id_no, //证件号码
									bankName: this.state.selectedBank.bankName, //银行卡名
									pageParams: this.state.pageParams,
									repayMark: pageParams.repayMark,
									unAccountAmount: pageParams.unAccountAmount,
									unRepayAmount: pageParams.unRepayAmount,
									channelNo: data.channelNo || null,
									preTransNo: data.preTransNo || null
								})}`
							});
						} else {
							this.props.history.push({
								pathname: `/backPay`,
								state: {
									fromType: pageParams.fromType,
									...data,
									billNo: params.params.billNo,
									amount: this.state.amount, // 还款金额
									sucessPhoneNo: data.bank_mobile_new,
									pageParams: this.state.pageParams,
									repayMark: pageParams.repayMark,
									unAccountAmount: pageParams.unAccountAmount,
									unRepayAmount: pageParams.unRepayAmount,
									channelNo: data.channelNo || null,
									preTransNo: data.preTransNo || null
								}
							});
						}
					} else {
						Toast.info(res.message, 2);
					}
				})
				.catch(() => {
					Toast.hide();
				});
		} else {
			Toast.info("请选择还款方式", 2);
		}
	};

	/**确认还款 */
	postInform() {
		const { selectedBank, amount, selectTools } = this.state;
		console.log(selectedBank, selectTools);
		if (!selectTools["alipay"] && !selectedBank) {
			Toast.info("请先添加银行卡", 2);
			return;
		}
		if (
			!selectTools["alipay"] &&
			selectedBank &&
			parseFloat(selectedBank.maxAmt) < parseFloat(amount)
		) {
			Toast.info("该银行卡已限额，请选择其他银行卡或者其他支付方式", 2);
			return;
		}
		dropByCacheKey("authenticatePay");
		yhTools.debounceNew(this.submitPay, 500)();
	}
	/**添加银行卡 */
	addBankCard() {
		this.props.history.push(`/xhdAddBank?from=05`);
	}
	/**切换支付方式 */
	changePaytool(tool) {
		let newTool = {};
		for (let key in this.state.selectTools) {
			if (key === tool) {
				newTool[key] = true;
			} else {
				newTool[key] = false;
			}
		}
		console.log(newTool);
		this.setState({
			selectTools: newTool
		});
	}

	/**更换银行卡 */
	changeBankCard() {
		this.props.history.push("/xhdBankList?from=05");
	}
	/*******************点击事件 end************************/
	/**获取banner */
	getBannerList() {
		const params = {
			url: InterfaceG.getChannelBannerList,
			params: {
				pageType: "XHF_REPAYMENT_PAGE",
				productNo: "601"
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			const { code, data = {} } = res;
			if (code == "0") {
				let bannerList = [];
				let bannerObj = data["1"] && data["1"].length > 0 ? data["1"]["0"] : {};
				bannerObj["link"] = bannerObj.linkUrl;
				bannerList.push(bannerObj);
				this.setState({
					bannerList
				});
			}
		});
	}
	/**渲染 */
	render() {
		const {
			amount,
			selectedBank,
			showAlipayRepaymentBtn,
			selectTools,
			pageParams = {},
			bannerList
		} = this.state;
		let pathNameParams = pageParams.backPath;
		console.log(selectTools);
		const _pageParams = {
			header: {
				title: "还款",
				goBackPath: "/" + pathNameParams,
				fromPage: "repaymentMoney"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		return (
			<MainLayout pageParams={_pageParams}>
				<div className="xhf_repayment-box">
					<div className="top-money">
						<div className="money-tips">
							还款金额(元)
							{pageParams.type == "2" && (
								<img
									src={questionLine}
									alt=""
									onClick={() => {
										modalAlert(
											"提示",
											`还款金额含本金、利息（若有）及罚息（若有）`,
											[
												{
													text: "确认",
													onPress: () => { }
												}
											]
										);
									}}
								/>
							)}
						</div>
						<div className="money-num">{amount || "--"}</div>
						{pageParams.type == 1 && (
							<div className="money-text">
								本期剩余金额按年化利率15.4%计息（单利），可随时还款
							</div>
						)}
					</div>
					{
						/**是否有还款银行卡 */
						selectedBank ? (
							<HaveBankCard
								data={{ ...selectedBank, ...selectTools }}
								onClick={this.changeBankCard.bind(this)}
								onChange={this.changePaytool.bind(this, "bankcard")}
							/>
						) : (
							<NoBankCard onClick={this.addBankCard.bind(this)} />
						)
					}
					{
						/**是否显示支付宝还款 */
						showAlipayRepaymentBtn && yhTools.isSupportAlipay(this.version) && (
							<div
								style={
									showAlipayRepaymentBtn &&
									yhTools.isSupportAlipay(this.version) && {
										marginTop: "0.48rem"
									}
								}
								className="zfb-item"
								onClick={this.changePaytool.bind(this, "alipay")}
							>
								<img className="item-left-img" src={iconZfb} />
								<div className="pay-label">支付宝还款</div>
								<img
									className="item-right-arrow"
									src={selectTools.alipay ? iconChecked : iconCheck}
								/>
							</div>
						)
					}
					<a
						className="submit-btn a-gradient"
						id="bottomDom"
						onClick={this.postInform.bind(this)}
					>
						确认还款
					</a>
					<Banner bannerList={bannerList} history={this.props.history} />
				</div>
			</MainLayout>
		);
	}
}

export default xhfRepayment;
